#include "PhiolRemoteDeviceManager.h"

#include <assert.h>
#include <phidget21.h>

namespace Phiol
{

RemoteDeviceManager::RemoteDeviceManager( const std::string& serverID, const std::string& password )
	: DeviceManager(),
	  mOpenedUsingServerID( true ),
	  mPassword( password ),
	  mServerID( serverID ),
	  mServerAddress(),
	  mPort(0)
{
	openRemotelyWithServerID( serverID, password );
}

RemoteDeviceManager::RemoteDeviceManager( const std::string& serverAddress, int port, const std::string& password )
	: DeviceManager(), 
	  mOpenedUsingServerID( false ),
	  mPassword( password ),
	  mServerID(),
	  mServerAddress( serverAddress ),
	  mPort( port )
{
	openRemotelyWithServerAddress( serverAddress, port, password );
}

bool RemoteDeviceManager::isConnected() const
{
	int result = 0;
	int ret = CPhidgetManager_getServerStatus( getPhidgetManagerHandle(), &result );
	assert( ret==EPHIDGET_OK );
	bool connected = ( result==PHIDGET_ATTACHED );
	return connected;
}

void RemoteDeviceManager::openDevice( CPhidgetHandle phidgetHandle, int serialNumber )
{
	int ret = EPHIDGET_OK;
	if ( mOpenedUsingServerID )
	{ 
		ret = CPhidget_openRemote( phidgetHandle, serialNumber, getServerID().c_str(), getPassword().c_str() );
		assert( ret==EPHIDGET_OK );
	}
	else
	{
		ret = CPhidget_openRemoteIP( phidgetHandle, serialNumber, getServerAddress().c_str(), getPort(), getPassword().c_str() );
		assert( ret==EPHIDGET_OK );
	}
}

}